import React, { useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { EmptyPage, ProFileInput, MyNavBar } from "../../../../components";
import style from "./style.module.scss";
import { Dialog, Toast } from "react-vant";
import { useAppSelector } from "../../../../store/hooks";
import { useRequest } from "ahooks";
import { getProFile, deleteProFile } from "../../../../api/my";
import ErrorBoundary from "../../../../components/errorBoundary";

//  我的档案——档案数据类型
interface proFileRawState {
  diseaseBefore: string;
  diseaseMain: string;
  diseaseNow: string;
  archivesId: number;
  picture: string;
  treatmentEndTime: number;
  treatmentHospitalRecent: string;
  treatmentProcess: string;
  treatmentStartTime: number;
  userId: number;
}

const Index: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  //  当前页面上一层页面路径
  const path = searchParams.get("previousPath") as string;
  const [visible, setVisible] = useState(false);
  const userId = useAppSelector((state) => state.user.userInfo.userId);
  const sessionId = useAppSelector((state) => state.user.userInfo.sessionId);
  const [archivesId, setArchivesId] = useState<number>(1);
  //  用户查看自己的档案接口
  const { data: proFileData = null } = useRequest(async () => {
    const resp = await getProFile(userId, sessionId);
    let res;
  
    if (resp.result && resp.result.length > 0) {
      const { archivesId } = resp.result[0];
      setArchivesId(archivesId);
      res = [...resp.result];
      res = res.map((item) => ({
        ...item,
        treatmentStartTime: new Date(item.treatmentStartTime)
          .toLocaleDateString()
          .split("/")
          .join("-"),
        treatmentEndTime: new Date(item.treatmentEndTime)
          .toLocaleDateString()
          .split("/")
          .join("-"),
      }));
    }
    return res && (res[0] as proFileRawState);
  });

  //  删除用户档案接口
  const onDelete = async () => {
    const resp = await deleteProFile(archivesId, userId, sessionId);
    const { message, status } = resp;
    if (status === "0000") {
      Toast.success(message);
      setVisible(false);
      window.location.reload();
    }
  };

  return (
    <ErrorBoundary>
      <div className={style.myProFile}>
        {proFileData ? (
          <div className={style.proFile}>
            <MyNavBar
              title="我的档案"
              onClickLeft={() => navigate(-1)}
            ></MyNavBar>
            <ProFileInput labelText="[主要症状]"></ProFileInput>
            <div className={style.diseaseMain}>{proFileData.diseaseMain}</div>
            <ProFileInput labelText="[现病史]"></ProFileInput>
            <div className={style.diseaseNow}>{proFileData.diseaseNow}</div>
            <ProFileInput labelText="[既往病史]"></ProFileInput>
            <div className={style.diseaseBefore}>
              {proFileData.diseaseBefore}
            </div>
            <ProFileInput labelText="[治疗经历]"></ProFileInput>
            <div className={style.experience}>
              <div className={style.top}>
                <span className="treatmentHospitalRecent">
                  {proFileData.treatmentHospitalRecent}
                </span>
                <span className="treatmentTime">
                  {proFileData.treatmentStartTime +
                    ` - ` +
                    proFileData.treatmentEndTime}
                </span>
              </div>
              <div className="bottom">{proFileData.treatmentProcess}</div>
            </div>
            <ProFileInput labelText="[相关图片]"></ProFileInput>
            <img src={proFileData.picture} alt="" className={style.picture} />
            <div className={style.operate}>
              <button
                className={style.btn_delete}
                onClick={() => setVisible(true)}
              >
                删除
              </button>
              <button
                className={style.btn_edit}
                onClick={() => {
                  navigate(`/my/profile/edit_add?archivesId=${archivesId}`, {
                    state: proFileData,
                  });
                }}
              >
                编辑
              </button>
            </div>
            <Dialog
              visible={visible}
              showCancelButton
              onConfirm={() => {
                onDelete();
              }}
              onCancel={() => setVisible(false)}
            >
              <div className={style.desc}>您的档案将会被删除！</div>
            </Dialog>
          </div>
        ) : (
          <div className={style.empty}>
            <EmptyPage
              title="我的档案"
              desc="您还没有档案哦"
              path={path}
            ></EmptyPage>
            <button
              className={style.btn_add}
              onClick={() => navigate("/my/profile/edit_add?proFileData=''")}
            >
              添加
            </button>
          </div>
        )}
      </div>
    </ErrorBoundary>
  );
};

export default Index;
